"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const core_1 = require("@angular-devkit/core");
const schematics_1 = require("@angular-devkit/schematics");
const fse = require("fs-extra");
const defaults_1 = require("../defaults");
const source_root_helpers_1 = require("../../utils/source-root.helpers");
// type UpdateJsonFn<T> = (obj: T) => T | void;
// interface CpaasPackageInfoItem{
//   name: string;
// }
// interface CpaasConfigPartialType {
//   packages: CpaasPackageInfoItem[];
// }
function main(options) {
    const packageName = getAppNameFromPackageJson();
    options = transform(options);
    options.packageName = core_1.strings.dasherize(`${packageName}`);
    return schematics_1.chain([
        // updateTsConfig(),
        // updateCpaasConfig(options, packageName),
        updateRouterConfig(options),
        // (tree, context) =>
        //   isMonorepo(tree)
        //     ? noop()(tree, context)
        //     : chain([
        //         branchAndMerge(mergeWith(generateWorkspace(options, appName))),
        //         moveDefaultAppToApps(options.path, appName, options.sourceRoot),
        //       ])(tree, context),
        // addAppsToCliOptions(options.path, options.name, appName),
        schematics_1.branchAndMerge(schematics_1.mergeWith(generate(options))),
    ]);
}
exports.main = main;
function getAppNameFromPackageJson() {
    try {
        const packageFile = './package.json';
        // console.log(packageFile);
        // process.exit();
        if (!fse.existsSync(packageFile)) {
            return defaults_1.DEFAULT_DIR_ENTRY_APP;
        }
        const packageJson = fse.readJsonSync(packageFile);
        if (!packageJson.name) {
            return defaults_1.DEFAULT_DIR_ENTRY_APP;
        }
        let name = packageJson.name;
        name = name.replace(/[^\w.]+/g, '-').replace(/\-+/g, '-');
        return name[0] === '-' ? name.substr(1) : name;
    }
    catch (e) {
        return defaults_1.DEFAULT_DIR_ENTRY_APP;
    }
}
function transform(options) {
    const target = Object.assign({}, options);
    // const defaultSourceRoot =
    //   options.rootDir !== undefined ? options.rootDir : DEFAULT_PACKAGES_PATH;
    if (!target.name) {
        throw new schematics_1.SchematicsException('Option (name) is required.');
    }
    target.language = !!target.language ? target.language : defaults_1.DEFAULT_LANGUAGE;
    target.name = core_1.strings.dasherize(target.name);
    target.pageName = target.name;
    // target.path =
    //   target.path !== undefined
    //     ? join(normalize(defaultSourceRoot), target.path)
    //     : normalize(defaultSourceRoot);
    return target;
}
// function updateCpaasConfig(options: SimplePageOptions, defaultAppName: string) {
//   return (host: Tree) => {
//     if (!host.exists('.cpaasrc.json')) {
//       return host;
//     }
//     return updateJsonFile(
//       host,
//       '.cpaasrc.json',
//       (cpaasrc: CpaasConfigPartialType) => {
//         if(!cpaasrc.packages || cpaasrc.packages.find(item => item.name === options.packageName)) {
//           return cpaasrc;
//         }
//         cpaasrc.packages = [
//           {
//             name: options.packageName,
//           },
//           ...cpaasrc.packages,
//         ];
//         return cpaasrc;
//       },
//     );
//   };
// }
function updateRouterConfig(options) {
    return (host) => {
        const routerFileName = 'src/config/routers.ts';
        if (!host.exists(routerFileName)) {
            return host;
        }
        const routerSrc = host.read(routerFileName).toString('utf-8');
        const importStatement = `import ${core_1.strings.camelize(options.pageName)}RouterConfig from '../pages/${core_1.strings.dasherize(options.pageName)}/routers';\n`;
        const expendStatement = `\n  ...${core_1.strings.camelize(options.pageName)}RouterConfig,\n`;
        const routerResult = importStatement
            .concat(routerSrc)
            .replace(/(?<=\/\/ Insert New Router.*)\n/, expendStatement);
        host.overwrite(routerFileName, routerResult);
        return host;
    };
}
// function updateRouterConfigFile(
//   scripts: Record<string, any>,
//   options: SimplePageOptions,
//   defaultAppName: string,
// ) {
//   scripts[options.packageName] = '0.0.1';
// }
function generate(options) {
    // const path = join(options.path as Path, options.packageName);
    return schematics_1.apply(schematics_1.url(core_1.join('./files', options.language)), [
        schematics_1.template(Object.assign(Object.assign({}, core_1.strings), options)),
        // move(path),
        source_root_helpers_1.removeTemplateExt(),
    ]);
}
